﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows.Input;
using System.Xml.Linq;
using Mvvm;
using CodeIn.Ui;

namespace CodeIn.Modules.Misc.WelcomeScreen {
	public class WelcomeViewModel : BaseViewModel {
		public string RssFeedUrl { get; set; }
		public ObservableCollection<RssItem> ProjectUpdateItems { get; private set; }

		public WelcomeViewModel() {
			ProjectUpdateItems = new ObservableCollection<RssItem>();
		}

		public void ReloadRssFeed() {
			ProjectUpdateItems.Clear();

			Uri uri = new Uri(RssFeedUrl);
			WebClient wc = new WebClient();

			wc.DownloadStringCompleted += (s, e) => {
				UiHelper.Synchronize(() => {
					ProjectUpdateItems.Clear();
					if (e.Error != null)
						return;
					foreach (var item in ParseIncomingFeed(e.Result))
						ProjectUpdateItems.Add(item);
				});
			};

			wc.DownloadStringAsync(uri);
		}

		private RssItem[] ParseIncomingFeed(string feedData) {
			List<RssItem> ret = new List<RssItem>();

			XDocument doc = XDocument.Parse(feedData);
			var items = doc.Element("rss").Element("channel").Elements("item");
			foreach (var item in items) {
				Func<string, string> safelyGet = elem => item.Element(elem) != null ? item.Element(elem).Value : "";

				RssItem rssItem = new RssItem();
				rssItem.Title = ConvertHttpChars(safelyGet("title"));
				rssItem.Link = safelyGet("link");
				rssItem.Description = ConvertHttpChars(safelyGet("description"));
				rssItem.Author = ConvertHttpChars(safelyGet("author"));
				rssItem.Date = safelyGet("pubDate");
				ret.Add(rssItem);

				try {
					var dt = DateTime.Parse(rssItem.Date);
					rssItem.Date = string.Format("{0:00}/{1:00}/{2:00} @ {3:00}:{4:00}",
						dt.Day, dt.Month, dt.Year, dt.Hour, dt.Minute);
				} catch {
				}
			}

			return ret.ToArray();
		}

		private string ConvertHttpChars(string str) {
			return WebUtility.HtmlDecode(str);
		}

		private RelayCommand reloadRssFeedCommand;
		public ICommand ReloadRssFeedCommand {
			get {
				if (reloadRssFeedCommand == null)
					reloadRssFeedCommand = new RelayCommand(
						p => { ReloadRssFeed(); },
						p => true);
				return reloadRssFeedCommand;
			}
		}
	}

	public class RssItem {
		public string Title { get; set; }
		public string Link { get; set; }
		public string Description { get; set; }
		public string Author { get; set; }
		public string Date { get; set; }
	}
}
